/**
 * 
 * @origin https://blog.csdn.net/Kylincsg?type=blog
 * @desc 学习借鉴 暂时留存
 */

export const getObjType = obj => {
    var toString = Object.prototype.toString;
    var map = {
      '[object Boolean]': 'boolean',
      '[object Number]': 'number',
      '[object String]': 'string',
      '[object Function]': 'function',
      '[object Array]': 'array',
      '[object Date]': 'date',
      '[object RegExp]': 'regExp',
      '[object Undefined]': 'undefined',
      '[object Null]': 'null',
      '[object Object]': 'object'
    };
    if (obj instanceof Element) {
      return 'element';
    }
    return map[toString.call(obj)];
  };

  export const deepClone = data => {
    var type = getObjType(data);  
    var obj;
    if (type === 'array') {
      obj = [];
    } else if (type === 'object') {
      obj = {};
    } else {
      //不再具有下一层次
      return data;
    }
    if (type === 'array') {
      for (var i = 0, len = data.length; i < len; i++) {
        obj.push(deepClone(data[i]));
      }
    } else if (type === 'object') {
      for (var key in data) {
        obj[key] = deepClone(data[key]);
      }
    }
    return obj;
  };

  export const toggleGrayMode = (status) => {
    if (status) {
      document.body.className = document.body.className + ' grayMode';
    } else {
      document.body.className = document.body.className.replace(' grayMode', '');
    }
  };
   
  /**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
    if (fullscreenEnable()) {
      exitFullScreen();
    } else {
      reqFullScreen();
    }
  };
   
  /**
   * esc监听全屏
   */
  export const listenfullscreen = (callback) => {
    function listen() {
      callback()
    }
   
    document.addEventListener("fullscreenchange", function () {
      listen();
    });
    document.addEventListener("mozfullscreenchange", function () {
      listen();
    });
    document.addEventListener("webkitfullscreenchange", function () {
      listen();
    });
    document.addEventListener("msfullscreenchange", function () {
      listen();
    });
  };
   
  /**
   * 浏览器判断是否全屏
   */
  export const fullscreenEnable = () => {
    var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
    return isFullscreen;
  }
   
  /**
   * 浏览器全屏
   */
  export const reqFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
      document.documentElement.requestFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
      document.documentElement.webkitRequestFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
      document.documentElement.mozRequestFullScreen();
    }
  };
   
  /**
   * 浏览器退出全屏
   */
  export const exitFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
      document.exitFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
      document.webkitCancelFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
      document.mozCancelFullScreen();
    }
  };

  export const findParent = (menu, id) => {
    for (let i = 0; i < menu.length; i++) {
       if (menu[i].id === id) {
         return menu[i];
       }
       if (menu[i].children) {
         for (let j = 0; j < menu[i].children.length; j++) {
            const result = this.findParent(menu[i].children, id);
            if (result) {
              return result;
            }
          }
        }
      }
    return null;
}

export const diff = (obj1, obj2) => {
    delete obj1.close;
    var o1 = obj1 instanceof Object;
    var o2 = obj2 instanceof Object;
    if (!o1 || !o2) { /*  判断不是对象  */
      return obj1 === obj2;
    }
   
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
      return false;
      //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
    }
   
    for (var attr in obj1) {
      var t1 = obj1[attr] instanceof Object;
      var t2 = obj2[attr] instanceof Object;
      if (t1 && t2) {
        return diff(obj1[attr], obj2[attr]);
      } else if (obj1[attr] !== obj2[attr]) {
        return false;
      }
    }
    return true;
  }

  /**
   @函数描述: 生成随机len位数字
   @param {bumber} len 长度
   @param {Boolean} isDate 是否需要添加时间戳
 */
export const randomLenNum = (len, isDate) => {
    let random = '';
    random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
    if (isDate) random = random + Date.now();
    return random;
  };
   
  /**
   * 获取随机字符串
   * @param len 指定长度
   * @returns {string}
   */
  export const randomString = (len) => {
    len = len || 32;
    let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    let maxPos = $chars.length;
    let pwd = '';
    for(let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  /**
 * 打开小窗口
 * @param url 窗口地址
 * @param title 窗口名称
 * @param w 窗口宽度
 * @param h 窗口高度
 */
export const openWindow = (url, title, w, h) => {
    // Fixes dual-screen position                            Most browsers       Firefox
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top
   
    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height
   
    const left = ((width / 2) - (w / 2)) + dualScreenLeft
    const top = ((height / 2) - (h / 2)) + dualScreenTop
    const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)
   
    // Puts focus on the newWindow
    if (window.focus) {
      newWindow.focus()
    }
  }

  export const getTopUrl = () => {
    return window.location.href.split("/#/")[0];
  }

  /**
 * 获取url参数
 * @param name 参数名
 */
getUrlParams(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
 }
  
 /**
  * 获取url参数
  * @param name 参数名
  */
 export const getQueryString = (name) => {
   let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
   let r = window.location.search.substr(1).match(reg);
   if (r != null) return unescape(decodeURI(r[2]));
   return null;
 }

 /**
 * 校验对象是否有效
 * 可校验null,undefined,空串,空数组,空对象
 * 注意:数值0返回true
 * @param obj
 * @returns {boolean}
 */
export const isNull = (obj) => {
    //所有数值都非NULL 数值0表示有效
    if (!isNaN(obj)) {
      return true;
    }
    //校验null,undefined,空字符串
    if ((!!obj) === false) {
      return false;
    }
    //校验数组
    if (Array.isArray(obj)) {
      return obj.length === 0;
    }
    //校验对象
    if (typeof (obj) === 'object') {
      return Object.keys(obj).length === 0;
    }
    throw new Error("无法识别的对象");
  }

  /**
 * 列表转树 由于有递归使用了匿名函数
 * @param arr 列表数据
 * @param rootId 根结点id
 * @returns {[]}
 */
export const arrayToTree = (function arrayToTree(arr, rootId = 0) {
    let temp = [];
    let treeArr = arr;
    treeArr.forEach((item, index) => {
        if (item.parentId === rootId) {
          if (arrayToTree(treeArr, treeArr[index].id).length > 0) {
            // 递归调用此函数
            treeArr[index].children = arrayToTree(treeArr, treeArr[index].id);
          }
          temp.push(treeArr[index]);
        }
      }
    );
    return temp;
  });

  /**
 * 去掉复制文章时评论输入框的style的样式
 * @param stringStr 输入框的数据
 * @returns {HTMLDivElement}
 */
export const clearCommentStyle = (stringStr) => {
    return stringStr.replace(/<span\b[^>]*>/g, function(match) {
      // 使用正则表达式替换匹配到的 style 属性
      return match.replace(/style\s*=\s*["'][^"']*["']/g, '');
    });
  }

  /**
 * 页面【导出】表格 - 【GET】
 * @param name 导出页面的名称
 * @param host 导出的地址
 * @returns {HTMLDivElement}
 */
export const downloadExportGet = (name,host) => {
    fetch(host, {
      method: 'GET',
      headers: {
        'System-Platform': 2,
        'Blade-Auth': getStore({name: 'token'})
      }
    })
      .then(response => response.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
        a.click();
        window.URL.revokeObjectURL(url);
      });
  }
   
  /**
   * 页面【导出】表格 - 【POST】
   * @param name 导出页面的名称
   * @param host 导出的地址
   * @param data 请求的数据
   * @returns {HTMLDivElement}
   */
  export const downloadExportPost = (name,host,data) => {
    fetch(host, {
      method: 'POST',
      headers: {
        'System-Platform': 2,
        'Blade-Auth': getStore({name: 'token'}),
        'Content-Type': 'application/json;charset=UTF-8'
      },
      body: JSON.stringify(data)
    })
      .then(response => response.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
        a.click();
        window.URL.revokeObjectURL(url);
      });
  }
   
   

  /**
 * 通用 - 超过5个字符中间用 ... 代替
 * 处理前：大床房单间    处理后： 大床...间
 * @param  str 处理前-字符串
 * @param  num 数量
 * @return str 处理后-字符串
 */
export const commStringOmit = (str,num) => {
    if(str.length > num) {
      return str.substr(0, num - 2) + "..." + str.substr(-1);
    }
    return str;
  }

  /**
 * @函数描述: 相同的str，放到同一个数组里面
 * @param: {Array} array 原数组
 * @param: {String} str 相同的值
 * @return: {Array} integration
 **/
export const sortArr = (array, str) => {
    var arrList = [], textList = [], tmp;
    // 按照特定的参数将数组排序将具有相同值得排在一起
    array = array.sort(function(a, b) {
      var aStr = a[str], bStr = b[str];
      return aStr < bStr ? -1 : 1;
    });
    if(array.length) {
      tmp = array[0][str];
    }
    // 将相同类别的对象添加到统一个数组
    for(var i in array) {
      if(array[i][str] === tmp) {
        textList.push(array[i]);
      } else {
        tmp = array[i][str];
        arrList.push(textList);
        textList = [array[i]];
      }
    }
    // 将最后的内容推出新数组
    arrList.push(textList); //获取到所有整合数据
    // 终极整合
    var integration = [];
    arrList.forEach((item) => {
      var itemObj = {title: "", children: []};
      item.forEach((self) => {
        // 后端返回的结构只有这几个字段，其他的不用传到父组件，否则会匹配不上，造成后端数据与传递数据项不统一
        if(itemObj.title !== self[str]) {
          itemObj.title = self[str];
          itemObj.children.push(self);
        } else {
          itemObj.children.push(self);
        }
      });
      if(itemObj.title !== ''){
        integration.push(itemObj);
      }
    });
    return integration;
  }

  /**
 * @函数描述: 数组去重
 * @param: {Array} arr 原数组
 **/
export const arrayReduce = (data) => {
    return data.reduce((pre, cur) => {
      pre.indexOf(cur) === -1 && pre.push(cur);
      return pre;
    }, []);
  }

  /**
 * 判断是否含有图片
 * @param  str
 */
export const containsImgTag = (str) => {
    var pattern = /<img.*?>/ig;
    return pattern.test(str);
  }

  /**
 * 过滤图片 保留纯文本
 * @param  str
 * @return
 */
export const filterImgTags = (str) => {
    return str.replace(/<img\b[^>]*?>/gi, " ")
  }

  /**
 * 过滤文本 保留纯图片
 * @param  str base64地址
 * @param  reqData oss指令凭证
 * @return Array
 */
export const filterTextSaveImgSrc = (str,reqData) =>{
    let regex = /<img src="(.*?)"/g
    let matches = str.match(regex);
    let srcArr = []
    matches.forEach(item => {
      let srcData = item.split('"')[1]
      let base64ToImageStr = base64ToImage(srcData,reqData)
      srcArr.push(base64ToImageStr)
    })
    return srcArr
  }

  /**
 * base64转图片
 * @param  base64DataUrl base64地址
 * @param  OSSTokenData 获取oss指令凭证  后端配置生成（可几秒失效），前端不用去阿里云配置
 * @param  filename 图片的类型名称
 * @return oss图片地址
 */
export const OSSAndBase64ToImage = (base64DataUrl,OSSTokenData,filename) => {
    let arr = base64DataUrl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    let file =  new File([u8arr], `${filename}.${suffix}`, {
      type: mime,
    })
   
    let formKey = OSSTokenData.dir + randomString(12) + `-${file.name}`
    let formData = new FormData();
    formData.append('OSSAccessKeyId', OSSTokenData.accessid)
    formData.append('policy', OSSTokenData.policy)
    formData.append('Signature', OSSTokenData.signature)
    formData.append('key', formKey)
    formData.append('host', OSSTokenData.host)
    formData.append('dir', OSSTokenData.dir)
    formData.append("file", file);
   
    const xhr = new XMLHttpRequest();
   
    xhr.open('post', OSSTokenData.host);
   
    xhr.send(formData);
    return ossUrl + formKey
  }

  /**
 * 去除外层多余的父节点的选中值 undefined  =>  分层选中的数据含有title的，但不需要这个数据，
 * 主要用于tree组件父节点没key，去掉父节点的选中值 undefined
 * @param {array}  checkedUserIdList  选中的userId集合
 * @param {string} removeValue     当前元素等于要删除的值
 */
export const removeParentNode = (checkedUserIdList, removeValue) => {
    for(var i = 0; i < checkedUserIdList.length; i++) {
      if(checkedUserIdList[i] === removeValue) {
        checkedUserIdList.splice(i, 1);
      }
    }
    return checkedUserIdList
  }

  /**
 * @函数描述: 获取tree全部的key值集合
 * @param: {Array} data
 **/
export const getAllKeys = (data,name) => {
    let keys = [];
    for (let node of data) {
      if(node[name]){
        keys.push(node[name]);
      }
      if (node.children) {
        keys.push(...getAllKeys(node.children));
      }
    }
    return keys;
  }
   
  /**
   * @函数描述: 获取tree全部的value值集合
   * @param: {Array} data
   **/
   export const getAllNodes = (data) => {
      let nodes = [];
      for (let node of data) {
        if (node.userId) {
          nodes.push(node);
        }
        if (node.children) {
          nodes.push(...this.getAllNodes(node.children));
        }
      }
      return nodes;
   }

   /**
 * @函数描述: 模糊搜索下拉框精确匹配文字高亮
 * @param {object} content 下拉项的内容
 * @param {object} title 需要匹配的内容
 */
export const searchHeightLight = (content,title) =>{
    let reg = ''
    let dataToReplace  = `<span style="color: #02A7F0">${title}</span>`
    if (content.indexOf(title) !== -1) {
      reg = content.replace(title, dataToReplace);
    }else {
      reg = content;
    }
    return reg
  }

  export const getParams = () => {
	let url = location.search;
	let params = {};
	if(url.indexOf("?") === 0) {
		let strs = url.substr(1).replace(/\?/g, '&').split("&");
		for(let i = 0; i < strs.length; i++) {
			let kv = strs[i].split("=");
			params[kv[0]] = kv[1];
		}
	}
	return params;
}

/**
 * 全屏切换
 */
function toggleFullscreen() {
	if(document.fullscreenElement ||
		document.mozFullScreenElement ||
		document.webkitFullscreenElement ||
		document.msFullscreenElement) {
		if(document.exitFullscreen) {
			document.exitFullscreen();
		} else if(document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if(document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		} else if(document.msExitFullscreen) {
			document.msExitFullscreen();
		}
	} else {
		if(document.documentElement.requestFullscreen) {
			document.documentElement.requestFullscreen();
		} else if(document.documentElement.mozRequestFullScreen) {
			document.documentElement.mozRequestFullScreen();
		} else if(document.documentElement.webkitRequestFullscreen) {
			document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
		} else if(document.body.msRequestFullscreen) {
			document.body.msRequestFullscreen();
		}
	}
}

/**
 * 字符串转base64
 * @param str
 * @returns {string}
 */
function encodeBase64(str) {
	// 对字符串进行编码
	let encode = encodeURI(str);
	// 对编码的字符串转化base64
	return btoa(encode);
}
 
/**
 * base64转字符串
 * @param base64
 * @returns {string}
 */
function decodeBase64(base64) {
	// 对base64转编码
	let decode = atob(base64);
	// 编码转字符串
	return decodeURI(decode);
}
// 防止重复点击
let forbidRepeatClick = (function() {
	let instance = null;
	let canClick = true;
 
	function Build() {
		this.setClick = function(callback) {
			if(canClick) {
				canClick = false;
				callback()
				setTimeout(function() {
					canClick = true;
				}, 1000)
			} else {
				console.log('1s之内不能重复点击')
			}
		}
	}
 
 
	if(!instance) {
		instance = new Build();
	}
 
	return instance;
})()

/**
 * @函数描述: 防抖
 **/
export const debounce = (func, delay) => {
    let timeoutId;
    return function() {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        func.apply(this, arguments);
      }, delay);
    };
  }
   
  /**
   * @函数描述: 节流
   **/
  export const throttle = (func, delay) => {
    let timeoutId;
    return function() {
      if (!timeoutId) {
        timeoutId = setTimeout(() => {
          func.apply(this, arguments);
          timeoutId = null;
        }, delay);
      }
    };
  }
   
  /**
   * @函数描述: 让代码延迟执行
   * @param: {Number} numberMillis 睡眠的时间
   **/
  function sleep(numberMillis) {
      var now = new Date();
      var exitTime = now.getTime() + numberMillis;
      while (true) {
          now = new Date();
          if (now.getTime() > exitTime)
              return;
      }
  }


  /**
 * 评论复制功能
 * @param comment 评论对象
 */
export const clickCopyPower(comment) => {
    // 正则去标签化
    let copyContent = comment.content.replace(/(<([^>]+)>)/gi, "")
    // 添加一个input元素放置需要的文本内容
	const dataContainer = document.createElement('input');
	dataContainer.value = this.htmlDecode(copyContent);
	document.body.appendChild(dataContainer);
	// 选中并复制文本到剪切板
	dataContainer.select();
	document.execCommand('copy');
	// 移除input元素
	document.body.removeChild(dataContainer);
	this.$message.success('复制成功')
}
/**
 * 反转义html
 */
export const htmlDecode(text) => {
    //1.首先动态创建一个容器标签元素，如DIV
    var temp = document.createElement("div");
	//2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
    temp.innerHTML = text;
    //3.最后返回这个元素的innerText或者textContent，即得到经过HTML解码的字符串了。
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}

/**
 * @函数描述: 识别网址并添加a标签
 * @param: {string} text
 **/
export const replaceUrlsWithLinks(text) => {
	// 匹配网址的正则表达式
	var urlRegexContainHttp = /(https?:\/\/[^\s]+)/g
	var urlRegexContainWww = /(www\.[^\s]+)/g;
	var replacedText
	// 使用replace()方法将匹配到的网址替换为带有<a>标签的链接
	if(urlRegexContainHttp.test(text)){
		replacedText = text.replace(urlRegexContainHttp, function(url) {
			return '<a href="' + url + '" class="mention-link" target="_blank">' + url + '</a>';
		});
	}else {
		replacedText = text.replace(urlRegexContainWww, function(url) {
			return '<a href="http://' + url + '" class="mention-link" target="_blank">' + url + '</a>';
		});
	}
 
	return replacedText;
}

//  禁止图片粘贴
document.addEventListener('paste', function(event) {
	var items = event.clipboardData.items;
	for (var i = 0; i < items.length; i++) {
		if (items[i].type.indexOf('image') !== -1) {
			event.preventDefault();
			break;
		}
	}
});

/**
 * 计算当前时间与创建时间的时间差
 * @param date 生成评论数据的时间
 * @param timer 时间差
 */
export const timeDifference(date,timer) => {
	let dateTime = new Date(date).getTime();
	let currentDate = new Date().getTime()  // 毫秒
	let time = timer * 60 * 1000
	if(currentDate - dateTime > time){
		return false
	}else {
		return true
	}
}

/**
 * 日期格式化
 */
export function dateFormat(date = new Date(),format = "YYYY-MM-DD HH:MM:SS") {
    if (date != 'Invalid Date') {
      var o = {
        "M+": date.getMonth() + 1, //month
        "d+": date.getDate(), //day
        "h+": date.getHours(), //hour
        "m+": date.getMinutes(), //minute
        "s+": date.getSeconds(), //second
        "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
        "S": date.getMilliseconds() //millisecond
      }
      if (/(y+)/.test(format)){
        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o)
        if (new RegExp("(" + k + ")").test(format)){
          format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
      return format;
    }
    return '';
  }

   /**
 * 网址
 * @param {string} textval
*/
export function validateURL(textval) {
    const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
    return urlregex.test(textval)
}
 
/**
 * 邮箱
 * @param {*} s
 */
export function isEmail(s) {
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
 
export function validateEmail(email) {
    const re = /^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(email)
}
 
/**
 * 手机号码
 * @param {*} s
 */
export function isMobile(s) {
    return /^1[0-9]{10}$/.test(s)
}
 
/**
 * 电话号码
 * @param {*} s
 */
export function isPhone(s) {
    return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
 
/**
 * URL地址
 * @param {*} s
 */
export function isURL(s) {
    return /^http[s]?:\/\/.*/.test(s)
}
 
/* 小写字母*/
export function validateLowerCase(str) {
    const reg = /^[a-z]+$/
    return reg.test(str)
}
 
/* 大写字母*/
export function validateUpperCase(str) {
    const reg = /^[A-Z]+$/
    return reg.test(str)
}
 
/* 大小写字母*/
export function validatAlphabets(str) {
    const reg = /^[A-Za-z]+$/
    return reg.test(str)
}
 
/*验证pad还是pc*/
export const vaildatePc = function() {
     const userAgentInfo = navigator.userAgent;
     const Agents = ["Android", "iPhone","SymbianOS", "Windows Phone","iPad", "iPod"];
     let flag = true;
     for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
     }
   return flag;
 }
 
/**
 * 判断是否为整数
 */
export function validatenum(num, type) {
    let regName = /[^\d.]/g;
    if (type == 1) {
        if (!regName.test(num)) return false;
    } else if (type == 2) {
        regName = /[^\d]/g;
        if (!regName.test(num)) return false;
    }
    return true;
}
 
/**
 * 判断是否为小数
 */
export function validatenumord(num, type) {
    let regName = /[^\d.]/g;
    if (type == 1) {
        if (!regName.test(num)) return false;
    } else if (type == 2) {
        regName = /[^\d.]/g;
        if (!regName.test(num)) return false;
    }
    return true;
}
 
/**
 * 判断是否为空
 */
export function validatenull(val) {
    if (typeof val == 'boolean') {
        return false;
    }
    if (typeof val == 'number') {
        return false;
    }
    if (val instanceof Array) {
        if (val.length == 0) return true;
    } else if (val instanceof Object) {
        if (JSON.stringify(val) === '{}') return true;
    } else {
        if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
        return false;
    }
    return false;
}

/**
 * 判断身份证号码
 */
export function cardid(code) {
    let list = [];
    let result = true;
    let msg = '';
    var city = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外 "
    };
    if (!validatenull(code)) {
        if (code.length == 18) {
            if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
                msg = "证件号码格式错误";
            } else if (!city[code.substr(0, 2)]) {
                msg = "地址编码错误";
            } else {
                //18位身份证需要验证最后一位校验位
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x'];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                if (parity[sum % 11] != code[17]) {
                    msg = "证件号码校验位错误";
                } else {
                    result = false;
                }
 
            }
        } else {
            msg = "证件号码长度不为18位";
        }
 
    } else {
        msg = "证件号码不能为空";
    }
    list.push(result);
    list.push(msg);
    return list;
}

/**
 * 判断手机号码是否正确
 */
export function isvalidatemobile(phone) {
    let list = [];
    let result = true;
    let msg = '';
    var isPhone = /^0\d{2,3}-?\d{7,8}$/;
    //增加134 减少|1349[0-9]{7}，增加181,增加145，增加17[678]  
    if (!validatenull(phone)) {
        if (phone.length == 11) {
            if (isPhone.test(phone)) {
                msg = '手机号码格式不正确';
            } else {
                result = false;
            }
        } else {
            msg = '手机号码长度不为11位';
        }
    } else {
        msg = '手机号码不能为空';
    }
    list.push(result);
    list.push(msg);
    return list;
}

// import {saveAs} from 'file-saver';
 
// /**
//  * 下载文件（以图片为例）
//  * @param url  // 文件地址  "https://XXXX.com.XXX.png"
//  * @param fileName  // 文件名 "图片1"
//  * @param type  // 文件类型  png
//  */
// export const downHandle(url,fileName,type) => {
//     fetch(url).then(response => response.blob()).then(blob => {
//     saveAs(blob,`${fileName}.${type});
//     });
// }